package math

// 实现一个函数，求base的exponent次方，不得使用库函数，不需要考虑大数问题

var gInvalidinput = false

func Power(base float64, exponent int) float64 {
	if base == 0 && exponent < 0 {
		gInvalidinput = true
		return 0
	}
	absExponent := uint(exponent)
	if exponent < 0 {
		absExponent = uint(-exponent)
	}
	result := powerWithUnsignedExponent(base, absExponent)
	if exponent < 0 {
		result = 1.0 / result
		return result
	}
	return result
}

func powerWithUnsignedExponent(base float64, exponent uint) float64 {
	if exponent == 0 {
		return 1
	}
	if exponent == 1 {
		return base
	}
	result := powerWithUnsignedExponent(base, exponent>>1) // exponent>>1等价于exponent/2
	result *= result
	if exponent&0x1 == 1 { // 等价于 %2 ==1
		result *= base
	}
	return result
}
